/**
 * 存储服务
 */
import Cookies from 'js-cookie'

class StorageService {
  constructor() {
  }

  /**
   * 报错所有可能
   * @private
   */
  save(key,val,exp) {
    // 先转换成session
    let sessVal = null // 必须string

    if (typeof val === 'string') {
      sessVal = val
    } else {
      sessVal = JSON.stringify(val)
    }
    // 保存
    // session storage
    sessionStorage.setItem(key, sessVal)
    // local storage
    localStorage.setItem(key, sessVal)
    // cookies
    Cookies.set(key, sessVal, {expires: exp? exp:365})
    // flash
  }

  /**
   * 从可能的地方获取session
   * @private
   */
  get(key) {
    // session storage
    if (sessionStorage) {
      let tmpData = sessionStorage.getItem(key)
      if (tmpData) {
        this.save(key,tmpData)
        return JSON.parse(tmpData)
      }
    }
    // local storage
    if (localStorage) {
      let tmpData = localStorage.getItem(key)
      if (tmpData) {
        this.save(tmpData)
        return JSON.parse(tmpData)
      }
    }
    // cookies
    let tmpData = Cookies.get(key)
    if (tmpData) {
      this.save(tmpData)
      return JSON.parse(tmpData)
    }
    // flash
  }
  remove(key){
    // session storage
    if (sessionStorage) {
      let tmpData = sessionStorage.getItem(key)
      if (tmpData) {
        sessionStorage.removeItem(key)
      }
    }
    // local storage
    if (localStorage) {
      let tmpData = localStorage.getItem(key)
      if (tmpData) {
        localStorage.removeItem(key)
      }
    }
    // cookies
    let tmpData = Cookies.get(key)
    if (tmpData) {
      Cookies.remove(key)
    }
    // flash
  }
}


export default new StorageService()
